# -*- coding: utf-8 -*-
import scrapy
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings
from datetime import datetime
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.model.items import Box
from zc_core.util.http_util import retry_request
from zc_core.spiders.base import BaseSpider
from fjzfcg.rules import parse_order_list
from fjzfcg.utils.captcha import Captcha


class OrderSpider(BaseSpider):
    name = 'order'
    # 常用链接
    order_list_url = 'http://120.35.30.176/shopping/contractlist.htm'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderSpider, self).__init__(batchNo=batchNo, *args, **kwargs)

    def start_requests(self):
        settings = get_project_settings()
        auth = Captcha().order_list_regist()
        if auth:
            self.cookies = auth.get('cookie')
            self.x_token = auth.get('xtoken')
        else:
            raise Exception('鉴权验证失败')

        for page in range(1, settings.get('MAX_ORDER_PAGE', 500)):
            yield scrapy.FormRequest(
                method='POST',
                url=self.order_list_url,
                callback=self.parse_order_list,
                cookies=self.cookies,
                formdata={
                    'endTime': '',
                    'beginTime': '',
                    'end_price': '',
                    'begin_price': '',
                    'purch_org_name': '',
                    'order_id': '',
                    'gotoInputPage': '',
                    'currentPage': str(page),
                    'xToken': self.x_token,
                },
                meta={
                    'reqType': 'order_page',
                    'page': page
                },
                headers={
                    'Connection': 'keep-alive',
                    'Cache-Control': 'max-age=0',
                    'Upgrade-Insecure-Requests': '1',
                    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept-Encoding': 'gzip, deflate',
                    'Accept-Language': 'zh-CN,zh;q=0.9',
                },
                errback=self.error_back,
                dont_filter=True
            )

    def parse_order_list(self, response):
        page = response.meta.get('page', 1)
        order_list = parse_order_list(response)
        if order_list:
            self.logger.info('列表: page=%s, count=%s' % (page, len(order_list)))
            yield Box('order', self.batch_no, order_list)
        else:
            self.logger.info('列表为空: page=%s' % page)
